package org.example;

import org.apache.commons.codec.binary.Base64;

/**
 * ImageHelper
 *
 * @author Flynn
 * @version 1.0
 * @description Base64工具类
 * @email liufenglin@163.com
 * @date 2019/2/12
 */
public class ImageHelper {

    private static final String imgBase64Sign = "base64,";
    private static final String imgTypeSign = "data:image/";


    private static String getClearBase64(String imageBase64) {
        int index = imageBase64.indexOf(imgBase64Sign);
        return imageBase64.substring(index + imgBase64Sign.length());
    }

    public static String getTypeByBase64(String imageBase64) {
        int index = imageBase64.indexOf(imgTypeSign);
        String firstSubString = imageBase64.substring(index + imgTypeSign.length());
        int semicolonIndex = firstSubString.indexOf(";");
        return firstSubString.substring(0, semicolonIndex);
    }

    public static byte [] ImageBase64ToByteArray(String imageBase64) {
        String base64 = getClearBase64(imageBase64);
        return toByteArray(base64);
    }

    public static String byteArrayToBase64(byte [] bytes, String format) {
        String base64Str = new String(Base64.encodeBase64(bytes));
        return imgTypeSign + format + ";" + imgBase64Sign + base64Str;
    }

    private static byte [] toByteArray(String base64) {
        return new Base64().decode(base64);
    }

}
